const mysql = require('mysql2/promise');
const configService = require('../services/configService');
require('dotenv').config({ path: '../../.env' });

// 默认数据库配置（用于初始化）
const defaultDbConfig = {
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  charset: 'utf8mb4',
  timezone: '+08:00',
  acquireTimeout: 60000,
  timeout: 60000,
  reconnect: true
};

// 动态获取数据库配置
let dbConfig = { ...defaultDbConfig };
let pool = null;

// 初始化数据库连接池
const initDatabase = async () => {
  try {
    // 尝试从配置服务获取数据库配置
    const configDbConfig = await configService.getDatabaseConfig();
    dbConfig = {
      ...defaultDbConfig,
      ...configDbConfig
    };
  } catch (error) {
    console.warn('无法从配置服务获取数据库配置，使用默认配置:', error.message);
  }

  // 创建连接池
  pool = mysql.createPool({
    ...dbConfig,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
  });

  console.log('数据库连接池已初始化');
  return pool;
};

// 测试数据库连接
const testConnection = async () => {
  try {
    if (!pool) {
      await initDatabase();
    }
    const connection = await pool.getConnection();
    console.log('✅ 数据库连接成功');
    connection.release();
    return true;
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message);
    return false;
  }
};

// 执行查询的辅助函数
const query = async (sql, params = []) => {
  try {
    if (!pool) {
      await initDatabase();
    }
    const [rows] = await pool.execute(sql, params);
    return rows;
  } catch (error) {
    console.error('数据库查询错误:', error);
    throw error;
  }
};

// 执行事务的辅助函数
const transaction = async (callback) => {
  if (!pool) {
    await initDatabase();
  }
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const result = await callback(connection);
    await connection.commit();
    return result;
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

// 获取连接池（延迟初始化）
const getPool = async () => {
  if (!pool) {
    await initDatabase();
  }
  return pool;
};

module.exports = {
  getPool,
  query,
  transaction,
  testConnection,
  initDatabase
};
